#include<iostream>
#include<pthread.h>
#include<unistd.h>

namespace ThreadMoudle{
    class ThreadData{
        public:
            std::string _name;
            pthread_mutex_t* _lock;

            ThreadData(const std::string &name, pthread_mutex_t*lock)
            :_name(name)
            ,_lock(lock)
            {}
    };
    typedef void (*func_t)(ThreadData*td); // 提供线程名称的执行方法改名
    class Thread
    {
        public:
            Thread(const std::string& name,func_t f,ThreadData* td)
            :name(name)
            ,_func(f)
            ,_td(td)
            {}
            void Execute() {
                isrunning = true;
                _func(_td);
                isrunning = false;
            }
            static void* ThreadRoutine(void *args){//相当于Java的run（）方法（代码源？？）
                Thread *self = (Thread *)args;
                self->Execute();
                return nullptr;
            }
            bool start(){
                int n = ::pthread_create(&tid, nullptr, ThreadRoutine, this);
                if(n!=0)
                    return true;
                else
                    return false;
            }
            void stop(){
                if(isrunning)
                {
                    isrunning = false;
                    int n = ::pthread_cancel(tid);
                    if(n != 0)perror("stop");
                    else std::cout << "quit success!" << std::endl;
                    
                }
            }
            void join(){
                if(!isrunning)
                {
                    int n = ::pthread_join(tid, nullptr);
                    if(n != 0)
                    {
                        perror("join");
                    }
                    else{
                        std::cout << "wait success!" << std::endl;
                    }
                }
            }
            ~Thread(){
                if(isrunning)
                {
                    this->stop();
                    this->join();
                }
            }

        private:
            std::string name;
            pthread_t tid;//线程id
            bool isrunning;
            func_t _func;//线程要执行的回调函数(外部传入)
            ThreadData *_td;
    };
}